package com.xd.cloud.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xd.cloud.common.annotation.DataAuthValidate;
import com.xd.cloud.entity.core.*;
import com.xd.cloud.service.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xd.cloud.common.Constants;
import com.xd.cloud.common.bean.MessageBean;
import com.xd.cloud.common.bean.OrgBean;
import com.xd.cloud.common.bean.OrgTreeBean;
import com.xd.cloud.common.bean.UserBean;
import com.xd.cloud.common.util.DateUtil;
import com.xd.cloud.common.util.MD5;
import com.xd.cloud.dao.Page;
import com.xd.cloud.service.device.TeamService;

/**   
 * 用户、角色等相关的controller
 * @author: dhl
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private DicService dicService;
	@Autowired
	private TeamService teamService;
	@Autowired
	private UserDataAuthorityService userDataAuthorityService;
	@Autowired
	private DataAuthorityService dataAuthorityService;
	///////////////////////////////组织机构相关部分/////////////////////////////////////////////////////
	/**
	* 根据条件搜索机构列表
	* @return Object
	*/
	@RequestMapping(value = "/getOrgList")
	@ResponseBody
	public Object getOrgList(HttpServletRequest request, HttpServletResponse response) {
	//直接返回前台  
	String draw = request.getParameter("draw");  
	//数据起始位置  
	//String startIndex = request.getParameter("start");  
	//每页显示的条数 
	String num = request.getParameter("page");  
	String pageSize = request.getParameter("limit");   
	int sindex = Integer.parseInt(num);
	int ps = Integer.parseInt(pageSize);
	Page page = orgService.getAllOrg(sindex,ps);//roleService.getAllRole(sindex, ps);
	
	Map<Object, Object> info = new HashMap<Object, Object>();  
	List<OrgBean> list = new ArrayList();
	List<Object[]> orglist = page.getResult();
	if (orglist != null)
	{
		for (Object[] org:orglist)
		{
			OrgBean ob = new OrgBean();
			ob.setId((Integer)org[0]);
			ob.setPid((Integer)org[3]);
			ob.setName((String)org[1]);
			ob.setLinkman((String)org[5]);
			ob.setLinkphone((String)org[6]);
			Dic dic = dicService.getDisByType(Constants.INDUSTRY_TYPE,(Integer)org[7]+"");
			ob.setIndustrytypevalue(dic.getValue());
			ob.setPname((String)org[8]);
			list.add(ob);
		}
	}
	info.put("pageData", list);  
	info.put("total", page.getTotalCount()); 
	info.put("draw", draw);  
	
	return info;
	}
	
	/**
	* 返回id返回机构
	* @return Object
	*/
	@RequestMapping(value = "/getOrg")
	@ResponseBody
	public Object getOrg(HttpServletRequest request, int id) {

		Object object = orgService.getOrg(id);//roleService.getAllRole(sindex, ps);
		if (object != null && object instanceof Object[])
		{
			int childs = orgService.getChilds(id);
			OrgBean ob = new OrgBean();
			Object[] objs = (Object[])object;
			ob.setId((Integer)objs[0]);
			ob.setName((String)objs[1]);
			ob.setPid((Integer)objs[3]);
			ob.setLegal((String)objs[4]);
			ob.setLinkman((String)objs[5]);
			ob.setLinkphone((String)objs[6]);
			ob.setIndustrytype((Integer)objs[7]);
			ob.setPname((String)objs[8]);
			ob.setIntroduction((String)objs[9]);
			ob.setChilds(childs);
			return new MessageBean(true,"",ob);
		}
		else
		{
			return new MessageBean(false);
		}
	}
	
	
	/**
	* 返回树状Org
	* @return Object
	*/
	@RequestMapping(value = "/getTreeOrg")
	@ResponseBody
	public Object getTreeOrg(HttpServletRequest request, HttpServletResponse response) {
		User sessionUser = getSessionUser(request);
		List<Object[]> orglist = orgService.getAllOrg();//roleService.getAllRole(sindex, ps);
		List<OrgTreeBean> list = new ArrayList();
		if (orglist != null)
			{
			for (Object[] org:orglist)
			{
				OrgTreeBean ob = new OrgTreeBean();
				ob.setId(((Integer)org[0]).toString());
				ob.setpId(((Integer)org[3]).toString());
				if(ob.getId().equals("-1")) {
					ob.setName("所有公司");
					ob.setLevelFlag("0");
				}else {
					ob.setName((String)org[1]);
					ob.setLevelFlag("1");
				}
				list.add(ob);
			}
		}
	//	{id:${org.id}, pId:${(org.parent.id)!0}, name:"${org.name}"},
		return new MessageBean(true,"",list);
	}

	/**
	* 返回Tree（公司+车队）
	* @return Object
	*/
	@RequestMapping(value = "/getTreeOrgTeam")
	@ResponseBody
	public Object getTreeOrgTeam(HttpServletRequest request, HttpServletResponse response) {
		User sessionUser = getSessionUser(request);
		List<Object[]> orglist = orgService.getAllOrg();
		List<OrgTreeBean> list = new ArrayList<OrgTreeBean>();
		if (orglist != null){
			for (Object[] org:orglist){
				int companyId = (Integer)org[0];
				OrgTreeBean ob = new OrgTreeBean();
				ob.setId(String.valueOf(companyId));
				ob.setpId(((Integer)org[3]).toString());
				if(ob.getId().equals("-1")) {
					ob.setName("所有公司");
					ob.setLevelFlag("0");
				}else {
					ob.setName((String)org[1]);
					ob.setLevelFlag("1");
				}
				list.add(ob);
				//根据公司id查找车队集合
				List<Team> teamList = teamService.getTeamByCompanyId(companyId);
				if(teamList!=null && teamList.size()>0) {
					for(Team team:teamList) {
						ob = new OrgTreeBean();
						ob.setId(companyId+"_"+String.valueOf(team.getId()));
						ob.setpId(String.valueOf(companyId));
						ob.setName(team.getName());
						ob.setLevelFlag("2");
						list.add(ob);
					}
				}
			}
		}
		return new MessageBean(true,"",list);
	}
	/**
	* 返回Tree（公司+车队+车辆）
	* @return Object
	*/
	@RequestMapping(value = "/getTreeOrgTeamVehicle")
	@ResponseBody
	public Object getTreeOrgTeamVehicle(HttpServletRequest request, HttpServletResponse response) {
		List<Object[]> orglist = orgService.getAllOrg();
		List<OrgTreeBean> list = new ArrayList<OrgTreeBean>();
		Map<String,OrgTreeBean> map = new HashMap<String,OrgTreeBean>();
		if (orglist != null){
			for (Object[] org:orglist){
				int companyId = (Integer)org[0];
				OrgTreeBean ob = new OrgTreeBean();
				ob.setId(String.valueOf(companyId));
				ob.setpId(String.valueOf(org[3]));
				if(ob.getId().equals("-1")) {
					ob.setName("监控中心");
					ob.setLevelFlag("0");
				}else {
					ob.setName((String)org[1]);
					ob.setLevelFlag("1");
				}
				map.put(ob.getId(), ob);
				//根据公司id查找车辆
				List<Object[]> dataList2 = teamService.getVehicleByCompanyId(companyId);
				if (dataList2 != null && dataList2.size()>0) {
					for (Object[] item:dataList2){
						if(item[0]!=null) {
							ob = new OrgTreeBean();
							ob.setId(String.valueOf(item[0]));
							ob.setpId(String.valueOf(item[1]));
							ob.setName((String)item[2]);
							ob.setLevelFlag("3");
							map.put(ob.getId(), ob);
						}
					}
				}
				//根据公司id查找车队集合
				List<Object[]> dataList = teamService.getTeamVehicleByCompanyId(companyId);
				if (dataList != null && dataList.size()>0) {
					for (Object[] item:dataList){
						if(item[0]!=null) {
							ob = new OrgTreeBean();
							ob.setId(companyId+"_"+String.valueOf(item[0]));
							ob.setpId(String.valueOf(item[1]));
							ob.setName((String)item[2]);
							ob.setLevelFlag("2");
							map.put(ob.getId(), ob);
							ob = new OrgTreeBean();
							ob.setId(String.valueOf(item[3]));
							ob.setpId(companyId+"_"+String.valueOf(item[0]));
							ob.setName((String)item[5]);
							ob.setLevelFlag("3");
							map.put(ob.getId(), ob);
						}
					}
				}
			}
			if(map!=null && map.size()>0) {
				for(OrgTreeBean item:map.values()) {
					list.add(item);
				}
			}
		}
		return new MessageBean(true,"",list);
	}
	/**
	 * 获取所属行业
	 * @return Object
	 */
	@RequestMapping(value = "/getDic")
	@ResponseBody
	public Object getDic(HttpServletRequest request,String type) {
		List<Dic> list = dicService.getDisByType(type);
		return new MessageBean(true,"",list);
	}
	
	/**
	 * 保存公司
	 * @return Object
	 */
	@RequestMapping(value = "/saveOrg")
	@ResponseBody
	public Object saveOrg(HttpServletRequest request, Org org) {
		
		boolean flag = orgService.save(org);
		return new MessageBean(flag,flag?Constants.SUCCESS_1:Constants.ERROR_2);
	}
	
	/**
	 * 编辑公司
	 * @return Object
	 */
	@RequestMapping(value = "/updateOrg")
	@ResponseBody
	public Object updateOrg(HttpServletRequest request, Org org) {
		
		orgService.update(org);
		return new MessageBean(true,Constants.SUCCESS_2);
	}
	
	/**
	 * 删除公司
	 * @return Object
	 */
	@RequestMapping(value = "/delOrg")
	@ResponseBody
	public Object delOrg(HttpServletRequest request,int id) {
		
		boolean flag = orgService.remove(id);
		return new MessageBean(flag,flag?Constants.SUCCESS_3:Constants.ERROR_10);
	}
	
	///////////////////////////////用户相关部分/////////////////////////////////////////////////////
	/**
	 * 根据条件搜索用户列表
	 * @return Object
	 */
	@RequestMapping(value = "/getUserList")
	@ResponseBody
	public Object getUserList(HttpServletRequest request, HttpServletResponse response) {
		User sessionUser = getSessionUser(request);
		Integer sessionUserId = sessionUser.getId();
		//直接返回前台  
        String draw = request.getParameter("draw");  
        //数据起始位置  
//        String startIndex = request.getParameter("start");  
        //每页显示的条数 
        String num = request.getParameter("page");  
        String pageSize = request.getParameter("limit");   
        int sindex = Integer.parseInt(num);
        int ps = Integer.parseInt(pageSize);
       // Page page = userService.getAllUser(sindex, ps);//roleService.getAllRole(sindex, ps);
		//根据当前登录账号用户Id 进行查询用户数据
        Page page = userService.getAllUserBySessionUserId(sindex,ps,sessionUserId);
        Map<Object, Object> info = new HashMap<Object, Object>();  
        
    	List<UserBean> list = new ArrayList();
    	List<Object[]> userlist = page.getResult();
    	if (userlist != null)
    	{
    		for (Object[] user:userlist)
    		{
    			UserBean ob = new UserBean();
    			ob.setId((Integer)user[0]);
    			ob.setAccount((String)user[1]);
    			ob.setName((String)user[2]);
    			ob.setUpdatetime((Date)user[3]==null?"":DateUtil.timeTostrHMS((Date)user[3]));
    			ob.setStatus((Integer)user[4] == 0 ?Constants.USER_OK:Constants.USER_ERR);
    			ob.setOrgname((String)user[5]);
    			if (user[6] != null)
    			ob.setOrgid((Integer)user[6]);
				ob.setRoleName((String)user[7]);
    			list.add(ob);
    		}
    	}
    	info.put("pageData", list);  
    	info.put("total", page.getTotalCount()); 
    	info.put("draw", draw);  
        
		return info;
	}
	
	/**
	 * 保存用户
	 * @return Object
	 */
	@RequestMapping(value = "/saveUser")
	@ResponseBody
	public Object saveUser(HttpServletRequest request, int orgid,String account,String name,String password,int status) {
		User sessionUser = getSessionUser(request);
		Integer sessionUserId = sessionUser.getId();
		User curentUser = userService.get(sessionUserId);
		User user = new User();
		user.setAccount(account);
		user.setName(name);
		user.setUser(curentUser);
		MD5 md5 = new MD5();
		String encodepassword = md5.getMD5ofStr(password);
		user.setPassword(encodepassword);
		user.setStatus(status);
		user.setCreatetime(new Date());
		boolean flag = userService.saveUser(user,orgid);
		UserDataAuthority userDataAuthority = new UserDataAuthority();
		userDataAuthority.setUser(user);
		userDataAuthority.setDataAuthority(dataAuthorityService.get(Constants.Data.AUTHORITY));
		userDataAuthorityService.save(userDataAuthority);
		return new MessageBean(flag,flag?Constants.SUCCESS_1:Constants.ERROR_3);
	}
	
	/**
	 * 编辑用户
	 * @return Object
	 */
	@RequestMapping(value = "/resetUserPwd")
	@ResponseBody
	public Object resetUserPwd(HttpServletRequest request,int userid,String password) {
		
		User user = userService.get(userid);
		MD5 md5 = new MD5();
		String encodepassword = md5.getMD5ofStr(password);
		user.setPassword(encodepassword);
		user.setUpdatetime(new Date());
		boolean flag = userService.update(user);
		return new MessageBean(flag,flag?Constants.SUCCESS_2:Constants.ERROR_5);
	}
	
	/**
	 * 编辑用户
	 * @return Object
	 */
	@RequestMapping(value = "/updateUser")
	@ResponseBody
	public Object updateUser(HttpServletRequest request,int id,int orgid,String name,int status) {
		
		User user = userService.get(id);
		user.setName(name);
		user.setStatus(status);
		user.setUpdatetime(new Date());
		boolean flag = userService.updateUser(user,orgid);
		return new MessageBean(flag,flag?Constants.SUCCESS_2:Constants.ERROR_5);
	}
	
	/**
	 * 删除用户
	 * @return Object
	 */
	@RequestMapping(value = "/delUser")
	@ResponseBody
	public Object delUser(HttpServletRequest request,int id) {
		userDataAuthorityService.delUserDataAuthorityByUserId(id);
		boolean flag = userService.remove(id);
		return new MessageBean(flag,flag?Constants.SUCCESS_3:Constants.ERROR_10);
	}

	/**
	 * 为用户分配角色
	 * @return Object
	 */
	@RequestMapping(value = "/{userid}/role/{roleid}")
	@ResponseBody
	public Object confUserRole(HttpServletRequest request, @PathVariable Integer userid,@PathVariable Integer roleid) {
		Role role = roleService.get(roleid);
		List<UserRole> noStatus = userRoleService.getByuseridNoStatus(userid);
		if( noStatus.size() >0 ){
			UserRole userRole = noStatus.get(0);
			userRole.setRole(role);
			userRoleService.update(userRole);
			return new MessageBean(true,userRole);
		}
		UserRole userRole = new UserRole();
		userRole.setUserid(userid);
		userRole.setRole(role);
		boolean save = userRoleService.save(userRole);
		return new MessageBean(true,userRole);
	}
	
	///////////////////////////////角色相关部分/////////////////////////////////////////////////////
	/**
	 * 根据条件搜索角色列表
	 * @return Object
	 */
	@RequestMapping(value = "/getRoleList")
	@ResponseBody
	public Object getRoleList(HttpServletRequest request, HttpServletResponse response) {
		//直接返回前台  
        String draw = request.getParameter("draw");  
        //数据起始位置  
//        String startIndex = request.getParameter("start");  
        //每页显示的条数 
        String num = request.getParameter("page");  
        String pageSize = request.getParameter("limit");   
        int sindex = Integer.parseInt(num);
        int ps = Integer.parseInt(pageSize);
        Page page = roleService.getAllRole(sindex, ps);
        
        Map<Object, Object> info = new HashMap<Object, Object>();  
        
        info.put("pageData", page.getResult());  
        info.put("total", page.getTotalCount()); 
        info.put("draw", draw);  
        
		return info;
	}
	
	/**
	 * 保存角色
	 * @return Object
	 */
	@RequestMapping(value = "/saveRole")
	@ResponseBody
	public Object saveRole(HttpServletRequest request, String name,String authority) {
		
		boolean flag = roleService.save(name,authority);
		return new MessageBean(flag,flag?Constants.SUCCESS_1:Constants.ERROR_1);
	}
	
	/**
	 * 更新角色
	 * @return Object
	 */
	@RequestMapping(value = "/updateRole")
	@ResponseBody
	public Object updateRole(HttpServletRequest request,int id, String name,String authority) {
		boolean flag = roleService.update(id, name,authority);
		return new MessageBean(flag,flag?Constants.SUCCESS_2:Constants.ERROR_1);
	}
	
	/**
	 * 删除角色
	 * @return Object
	 */
	@RequestMapping(value = "/delRole")
	@ResponseBody
	public Object delRole(HttpServletRequest request,int id) {
		
		boolean flag = roleService.remove(id);
		return new MessageBean(flag,flag?Constants.SUCCESS_3:Constants.ERROR_10);
	}
	/////////////////////////////////////////////////////////////////////////////////////////////
}